package com.example.common.handler;

import com.example.common.api.R;
import com.example.common.enums.ResponseCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

/**
 * 全局异常处理
 * @author mie
 */
@Slf4j
@RestControllerAdvice
public class RestExceptionHandler {
    
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.OK)
    public R methodArgumentNotValidException(MethodArgumentNotValidException e){
        log.error("参数校验异常:",e);
        return R.failed(ResponseCode.FAILED.getMsg()+";"+e.getBindingResult().getAllErrors().stream().map(ObjectError::getDefaultMessage).collect(Collectors.joining(";")));
    }
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.OK)
    public R businessException(BusinessException e){
        log.warn("业务异常:",e);
        return R.ok(e.getCode(),e.getMsg());
    }
    @ExceptionHandler(BadCredentialsException.class)
    @ResponseStatus(HttpStatus.OK)
    public R badCredentialsException(BadCredentialsException e){
        log.warn("登陆异常：",e);
        return R.ok(HttpStatus.UNAUTHORIZED.value(),e.getMessage());
    }
    /**
     * 默认处理全局异常
     * @param e Exception
     * @return R<String>
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public R<String> exception(Exception e){
        log.error("系统异常: ",e);
        return R.failed("系统异常");
    }
}